import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElButton, ElTable, ElTableColumn, ElInput, ElMessage } from 'element-plus'
import type { tableStateType } from './typings'
import useVuexGetters from '~/hooks/useVuexGetters'
import useWebsocket from '~/hooks/useWebsocket'
import NoticeMes from '../../components/noticeMes'

export default defineComponent({
  props: ['swInitFun'],
  setup(props, { expose }) {
    const store = useStore()
    const state = reactive<tableStateType>({
      configTable: [
        {
          leakageUAlarmLimit: 0,
          leakageIAlarmLimit: 0, // 漏电报警限值
          leakageIProtectLimit: 0, // 漏电跳闸限值
          leakageUProtectLimit: 0, // 漏电跳闸限值
          lowerIAlarmLimit: 0, // 欠流报警限值
          overIAlarmLimit: 0, // 过流报警限值
          overUAlarmLimit: 0, // 供电电压过压报警限制
          lowerUAlarmLimit: 0, // 供电电压欠压报警限制
          overProtectLimit: 0
        }
      ],
      // 运行参数
      execTable: [
        {
          heartBeatInterval: 60, // 工况间隔
          actualDataReportInterval: 15 // 通信间隔
        }
      ],
      visible: false
    })
    const userState = useVuexGetters('user', ['token'])
    const webSocketRef = useWebsocket('/websocket/protocol/lampctrl', {
      // 接收数据回调
      onmessage: swInitFun
    })
    const noticeRef = ref()
    const openParams = (type: string, row?: any) => {
      state.visible = true
      if (type === 'one') {
        // 单个设备
        state.id = row.id
        state.data = [row]
        const arr = JSON.parse(row.configData)
        const configData = {
          leakageUAlarmLimit: arr.leakageUAlarmLimit || 0,
          leakageIAlarmLimit: arr.leakageIAlarmLimit || 0, // 漏电报警限值
          leakageIProtectLimit: arr.leakageIProtectLimit || 0, // 漏电跳闸限值
          leakageUProtectLimit: arr.leakageUProtectLimit || 0, // 漏电跳闸限值
          lowerIAlarmLimit: arr.lowerIAlarmLimit || 0, // 欠流报警限值
          overIAlarmLimit: arr.overIAlarmLimit || 0, // 过流报警限值
          overUAlarmLimit: arr.overUAlarmLimit || 0, // 供电电压过压报警限制
          lowerUAlarmLimit: arr.lowerUAlarmLimit || 0, // 供电电压欠压报警限制
          overProtectLimit: arr.overProtectLimit || 0
        }
        state.configTable = [configData]
        const arr2 = JSON.parse(row.execParam)
        const execParam = {
          actualDataReportInterval: arr2.actualDataReportInterval || 15,
          heartBeatInterval: arr2.heartBeatInterval || 60
        }
        state.execTable = [execParam]
      } else {
        // 多个设备
        state.data = row
        state.id = row.map((item: any) => item.id).join(',')
        const configData = {
          leakageUAlarmLimit: 0,
          leakageIAlarmLimit: 0, // 漏电报警限值
          leakageIProtectLimit: 0, // 漏电跳闸限值
          leakageUProtectLimit: 0, // 漏电跳闸限值
          lowerIAlarmLimit: 0, // 欠流报警限值
          overIAlarmLimit: 0, // 过流报警限值
          overUAlarmLimit: 0, // 供电电压过压报警限制
          lowerUAlarmLimit: 0, // 供电电压欠压报警限制
          overProtectLimit: 0
        }
        state.configTable = [configData]
        const execParam = {
          actualDataReportInterval: 15,
          heartBeatInterval: 60
        }
        state.execTable = [execParam]
      }
    }

    //  保存
    const submitForm = async (type: number) => {
      const params = {
        configData: JSON.stringify(state.configTable[0]),
        execParm: JSON.stringify(state.execTable[0]),
        sendState: type,
        lampNodeIds: state.id
      }
      if (type === 0) {
        // 保存
        const res = await store.dispatch('singleLamp/SaveParamSet', params)
        if (res.code === 200) {
          ElMessage({ type: 'success', message: res.msg })
          state.visible = false
        }
      } else if (type === 1) {
        // 下发
        const res = await store.dispatch('singleLamp/SendParamSet', { lampNodeIds: state.id })
        if (res.code === 200) {
          ElMessage({ type: 'success', message: res.msg })
          state.visible = false
        }
        const arr = state.data?.map((item) => item.id)
        const codes = state.data?.map((item) => item.code)
        arr?.forEach((item) => {
          const websockParams = {
            token: userState.token.value,
            deviceId: item,
            commandCode: '001'
          }
          webSocketRef.value!.send(JSON.stringify(websockParams))
        })

        noticeRef.value.initMes({
          deviceId: state.id,
          commandCode: '001',
          token: userState.token.value,
          title: '参数下发',
          key: '001',
          arrStr: codes?.join(','),
          callBack: () => {}
        })
      }
    }
    function swInitFun(data?: any) {
      if (data.data.status === '2') {
        noticeRef.value.stateFun({
          key: data.commandCode,
          state: 'error',
          errText: data.data.message || '命令下发失败！'
        })
        return false
      }
      // 单个回路
      if (data.data.status === 1)
        noticeRef.value.stateFun({
          key: data.commandCode,
          id: '',
          title: '参数下发'
        })
    }
    //  取消
    const resetForm = () => {
      state.configTable = [
        {
          leakageUAlarmLimit: 0,
          leakageIAlarmLimit: 0, // 漏电报警限值
          leakageIProtectLimit: 0, // 漏电跳闸限值
          leakageUProtectLimit: 0, // 漏电跳闸限值
          lowerIAlarmLimit: 0, // 欠流报警限值
          overIAlarmLimit: 0, // 过流报警限值
          overUAlarmLimit: 0, // 供电电压过压报警限制
          lowerUAlarmLimit: 0, // 供电电压欠压报警限制
          overProtectLimit: 0
        }
      ]
      state.execTable = [
        {
          heartBeatInterval: 60, // 工况间隔
          actualDataReportInterval: 15 // 通信间隔
        }
      ]
      state.visible = false
    }

    expose({ openParams })
    onMounted(() => {})
    return () => {
      return (
        <ElDialog
          title="参数设置"
          modelValue={state.visible}
          beforeClose={resetForm}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          width={1100}
          v-slots={{
            footer: () => (
              <>
                <ElButton onClick={resetForm}>取消</ElButton>
                <ElButton type="primary" onClick={() => submitForm(0)}>
                  保存
                </ElButton>
                <ElButton type="primary" onClick={() => submitForm(1)}>
                  下发
                </ElButton>
              </>
            )
          }}
        >
          <div style="margin:20px 0;font-size: 16px;">
            <span style="font-weight:bold">警报设置：</span>
            <i class="el-icon-question" style="margin-right:2px"></i>参数值{'>'}
            0开启警报，参数值≤0关闭警报。
          </div>
          <ElTable data={state.configTable} border>
            <ElTableColumn label="漏电压" align="center">
              <ElTableColumn
                prop="leakageUAlarmLimit"
                label="报警限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.leakageUAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">V</span>
                    </>
                  )
                }}
              ></ElTableColumn>
              <ElTableColumn
                prop="leakageUProtectLimit"
                label="跳闸限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.leakageUProtectLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">V</span>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTableColumn>
            <ElTableColumn label="漏电流" align="center">
              <ElTableColumn
                prop="leakageIAlarmLimit"
                label="报警限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.leakageIAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">A</span>
                    </>
                  )
                }}
              ></ElTableColumn>
              <ElTableColumn
                prop="leakageIProtectLimit"
                label="跳闸限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.leakageIProtectLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">A</span>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTableColumn>
            <ElTableColumn label="电流" align="center">
              <ElTableColumn
                prop="lowerIAlarmLimit"
                label="欠流限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.lowerIAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">A</span>
                    </>
                  )
                }}
              ></ElTableColumn>
              <ElTableColumn
                prop="overIAlarmLimit"
                label="过流限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.overIAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">A</span>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTableColumn>
            <ElTableColumn label="电压" align="center">
              <ElTableColumn
                prop="lowerUAlarmLimit"
                label="欠压限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.lowerUAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">V</span>
                    </>
                  )
                }}
              ></ElTableColumn>
              <ElTableColumn
                prop="overUAlarmLimit"
                label="过压限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.overUAlarmLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">V</span>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTableColumn>
            <ElTableColumn label="功率因数" align="center">
              <ElTableColumn
                prop="overProtectLimit"
                label="越限值"
                align="center"
                v-slots={{
                  default: (scope: any) => (
                    <>
                      <ElInput
                        v-model={scope.row.overProtectLimit}
                        style="width: 70px;"
                        placeholder="请输入"
                      />
                      <span style="padding:0 4px;">V</span>
                    </>
                  )
                }}
              ></ElTableColumn>
            </ElTableColumn>
          </ElTable>
          <div style="margin: 20px 0;font-size: 16px;">
            <span style="font-weight:bold">运行参数设置：</span>
            <i class="el-icon-question" style="margin-right:2px"></i>默认按照设备出厂参数运行。
          </div>
          <ElTable data={state.execTable} border>
            <ElTableColumn
              label="通信间隔"
              align="center"
              prop="heartBeatInterval"
              v-slots={{
                default: (scope: any) => (
                  <>
                    <ElInput
                      v-model={scope.row.heartBeatInterval}
                      style="width: 200px;"
                      placeholder="请输入"
                    />
                    <span style="padding:0 6px">秒</span>
                  </>
                )
              }}
            ></ElTableColumn>
            <ElTableColumn
              label="工况间隔"
              align="center"
              prop="actualDataReportInterval"
              v-slots={{
                default: (scope: any) => (
                  <>
                    <ElInput
                      v-model={scope.row.actualDataReportInterval}
                      style="width: 200px;"
                      placeholder="请输入"
                    />
                    <span style="padding:0 6px">分钟</span>
                  </>
                )
              }}
            ></ElTableColumn>
          </ElTable>
          <NoticeMes ref={noticeRef} />
        </ElDialog>
      )
    }
  }
})
